/*
 * @Author: your name
 * @Date: 2020-05-12 14:32:44
 * @LastEditTime: 2020-05-21 14:26:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tuyibo\servers\models\user\m_user_favorior.js
 */ 
const Sequelize = require('sequelize')

module.exports = (sequelize, DataTypes ) => {

  class user_favorites extends Sequelize.Model {

    // 根据用户id查出收藏过的图片
    static async getImageIdByUid(uid){
      var list=await this.findAll({attributes:['img_id'],where:{user_id:uid,favorite_type:0},raw:true})
      return list;
    }

    //   检查该用户是否已经点赞过该图片
    static async checkUserLike(pars) {
      var user_id = pars.uid;
      var img_id = pars.image_id
      var sql = `SELECT id FROM user_img where user_id=${user_id} and img_id=${img_id} and operate=1`
      var result = await this.raw(sql)
      return result;
    }
    //   检查该用户是否已经收藏过该图片
    async checkUserCollect(pars) {
      var [user_id,img_id,favorite_type=0]=[pars.uid,pars.image_id,pars.favorite_type]
      let condition = {
        attributes: ['id'],
        raw: true,
        where:{user_id,img_id,favorite_type}
      }
      let result=await this.findOne(condition)
      return result;
    }

    // 删除收藏
    async deleteCollect(pars) {
      let result = await this.destroy({
        'where': {
          'img_id': pars.image_id,
          'user_id': pars.uid,
          'operate': 2
        }
      })
      return result;
    }

    // 添加收藏
    async pushCollect(pars) {
      let result = await this.create({
        img_id: pars.image_id,
        user_id: pars.uid,
        operate: 2
      })
      return result;
    }
    // 获取某一图片的收藏数量
    async getCollectCount(id){
      let result=await this.count({
        where:{
          img_id:id,
          operate:2
        }
      })
      return result;
    }

  }
  
  user_favorites.init({
    comment: "用户收藏表",
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    img_id: { type: DataTypes.INTEGER },
    favorite_type: { type: DataTypes.INTEGER },
    user_id: { type: DataTypes.INTEGER },
    create_time:{ type: DataTypes.INTEGER, comment:'收藏时间'}
  }, {
    sequelize,
    modelName: 'user_favorites',
    freezeTableName: true,
    timestamps: false
  });
  return user_favorites;
}